/**
 * Created by Administrator on 2017/7/20.
 */
(function() {
    "use strict";
    var app = angular.module("angularApp");
    app.controller('userCtrl', function ($scope, $http,$uibModal,fac) {
        $scope.search = {};
        $scope.pageModel = {};
        $scope.find = function(pageNo){
            $.extend($scope.search,{currentPage:pageNo||$scope.pageModel.currentPage||1,pageSize:$scope.pageModel.pageSize||10});
            fac.getPageResult("../sys/listUser",$scope.search,function(data){
                $scope.pageModel = data;
            });
        };
        $scope.find();
        //删除
        $scope.del = function(item){
            confirm("确认删除用户吗？",function(){
                $http.get("../sys/delUser?ids="+item.id).success(function(resp){
                    if(resp.code === 0){
                        $scope.find();
                    }else{
                        alert(resp.msg);
                    }
                })
            });
        }

        //添加与保存instance
        $scope.edit = function(item){
            var copy = angular.extend({},item);
            var modal = $uibModal.open({
                animation: false,
                size:'lg',
                templateUrl: 'view/sys/user.modal.html',
                controller: 'userModalCtrl'
                ,resolve: {item: copy}
            });
            modal.result.then(function () {
                $scope.find();
            }, function () {
                console.info('Modal dismissed at: ' + new Date());
            });
        };

    });

    app.controller('userModalCtrl', function($scope,$rootScope,$http,$uibModalInstance,$q,fac,item) {

       var  sceneList = fac.treeToFlat($rootScope.filteredSceneTree);

        item.powerList = item.power?item.power.split(","):[];
        $scope.categories = $.extend(true,[],app.categories);


        $scope.item = item;
        $scope.temp = {};
        $scope.instances = [];

        function initInstances(ids,edit){
            if( /^[\d,]+$/.test(ids)){
                var param = {currentPage:1,pageSize:1000,inIds:ids};
                fac.getPageResult("../instance/list",param,function(pageModel){
                    pageModel.data.forEach(function(n){
                        var node = sceneList.find(function(s){return s.id == n.sceneId});
                        if(node){
                            var sceneName = (node.ptexts?node.ptexts+ " > ":"") +node.text;
                            $scope.instances.push({id:n.id,edit:edit,name:sceneName+"："+n.name});
                        }
                    })
                });
            }
        }
        initInstances(item.readInstanceIds,false);
        initInstances(item.writeInstanceIds,true);

        $scope.getCheckClass = function(powerList,power){
            var checked = powerList.indexOf(power)!=-1;
            return	{'green':checked,'glyphicon-check':checked,'red':!checked,'glyphicon-unchecked':!checked};
        }
        /**
         * 给角色的某菜单按钮添加或删除权限
         */
        $scope.toggleAccess = function(powerList,power){
            var list = item.powerList;
            if(list.indexOf(power)==-1){
                list.push(power);
                if(list.indexOf(powerList[0])==-1){
                    list.push(powerList[0]);
                }
            }else{
                list.splice(list.indexOf(power),1);
                if(powerList.indexOf(power)==0){
                    powerList.forEach(function(n){
                        if(list.indexOf(n)>-1){
                            list.splice(list.indexOf(n),1);
                        }
                    })
                }
            }
        }
        /**
         * 全选与反选某菜单的铵钮权限
         */
        $scope.checkAll = function(menu){
            if(menu.all==1){
                menu.powerList.forEach(function(n){
                    if(item.powerList.indexOf(n)>-1){
                        item.powerList.splice(item.powerList.indexOf(n),1);
                    }
                })
                menu.all = 0;
            }else{
                menu.powerList.forEach(function(n){
                    if(item.powerList.indexOf(n)==-1){
                        item.powerList.push(n);
                    }
                })
                menu.all = 1;
            }
        }

        $scope.resetInstance = function(host,node){
            delete host.obj;
        }

        $scope.findInstance = function(sceneId,val){
            if(!sceneId){
                return;
            }
            var deferred = $q.defer()
            var param = {sceneId:sceneId,name:val};
            $.extend(param,{currentPage:1,pageSize:10});
            param.notInIds  = $scope.instances.reduce(function(ret,n){ret.push(n.id);return ret },[]).join();
            fac.getPageResult("../instance/list",param,function(pageModel){
                deferred.resolve(pageModel.data);
                if(!pageModel.data.length){
                    alert("无可选样式！")
                }
            });
            return deferred.promise;
        };

        $scope.addInstance = function(temp){
            var instanceId = temp.obj.id;
            var exists = $scope.instances.find(function(n){return n.id == instanceId});
            if(!exists){
                var node = sceneList.find(function(s){return s.id == temp.sceneId});
                var sceneName = (node.ptexts?node.ptexts+ " > ":"") +node.text;
                $scope.instances.push({id:instanceId,name:sceneName+"："+temp.obj.name});
            }
            delete temp.obj;
        }
        $scope.save = function (form) {
            form.$setSubmitted(true);
            if (!form.$valid) {
                return;
            }
            item.power = item.powerList.join();
            item.readInstanceIds  = $scope.instances.reduce(function(ret,n){!n.edit && ret.push(n.id);return ret },[]).join();
            item.writeInstanceIds  = $scope.instances.reduce(function(ret,n){n.edit && ret.push(n.id);return ret },[]).join();
            $http.post("../sys/saveUser", item).success(function (resp, status, headers, config) {
                if (resp.code === 0) {
                    $uibModalInstance.close();
                } else {
                    alert(resp.msg);
                }
            })
        }
    });

})();